package com.unittec.zk.provider.exam.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unittec.zk.provider.exam.entity.ElQuAnswer;
import com.unittec.zk.provider.exam.entity.ElQuRepo;
import com.unittec.zk.provider.exam.enums.QuType;
import com.unittec.zk.provider.exam.utils.BeanMapper;
import com.unittec.zk.provider.utils.CopyUtils;
import com.unittec.zk.sdk.exam.domain.QuAnswerDTO;
import com.unittec.zk.sdk.exam.request.*;
import com.unittec.zk.sdk.root.internal.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.mapper.ElQuMapper;
import com.unittec.zk.provider.exam.entity.ElQu;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class ElQuService extends ServiceImpl<ElQuMapper, ElQu> {

    @Resource
    private ElQuAnswerService elQuAnswerService;

    @Resource
    private ElQuRepoService elQuRepoService;

    /**
     * 试题-分页
     *
     * @param req201006
     * @return
     */
    public Object getQuPage(Req201006 req201006) {
        req201006.setQuType(req201006.getParams().getQuType());
        req201006.setRepoIds(req201006.getParams().getRepoIds());
        req201006.setContent(req201006.getParams().getContent());
        //初始化条件构造器
        LambdaQueryWrapper<ElQu> qw = new LambdaQueryWrapper<>();

        //填充条件
        if (req201006.getQuType() > 0) {
            qw.apply("q.qu_type = "+req201006.getQuType());
        }
        if (req201006.getRepoIds() != null && req201006.getRepoIds().size() > 0) {
            String sql = "po.repo_id in (";
            for (String repoId : req201006.getRepoIds()) {
                sql = sql + "'" + repoId + "',";
            }
            sql = sql.substring(0, sql.length() - 1);
            sql = sql + ")";
            qw.apply(sql);
        }
        if (StrUtil.isNotBlank(req201006.getContent())) {
            qw.apply("q.content like '%"+req201006.getContent()+"%'");
        }

        //分页查询数据库
        Page<Map<String,Object>> page = this.baseMapper.getQuPage(new Page<Object>(req201006.getCurrent(),req201006.getSize()), qw);
        return page;
    }

    /**
     * 试题-增/改
     * @param req201008
     * @return
     */
    public Object saveOrUpdateQu(Req201008 req201008) {
        // 校验数据
        this.checkData(req201008, "");

        //如果没有传id，则自己生成
        ElQu qu = new ElQu();
        BeanMapper.copy(req201008, qu);

        // 保存问题
        this.saveOrUpdate(qu);

        // 保存全部答案
        elQuAnswerService.saveAll(qu.getId(), req201008.getAnswerList());

        // 保存 题-题库 关系
        elQuRepoService.saveAll(qu.getId(), qu.getQuType(), req201008.getRepoIds());
        return "Success";
    }

    /**
     * 校验题目信息
     *
     * @param qu
     * @param no
     * @throws Exception
     */
    public void checkData(Req201008 qu, String no) {


        if (StringUtils.isEmpty(qu.getContent())) {
            throw new BusinessException("题目内容不能为空！");
        }


        if (CollectionUtils.isEmpty(qu.getRepoIds())) {
            throw new BusinessException("至少要选择一个题库！");
        }

        List<QuAnswerDTO> answers = qu.getAnswerList();


        if (CollectionUtils.isEmpty(answers)) {
            throw new BusinessException("客观题至少要包含一个备选答案！");
        }


        int trueCount = 0;
        for (QuAnswerDTO a : answers) {

            if (a.getIsRight() == null) {
                throw new BusinessException("必须定义选项是否正确项！");
            }

            if (StringUtils.isEmpty(a.getContent())) {
                throw new BusinessException("选项内容不为空！");
            }

            if (a.getIsRight()==1) {
                trueCount += 1;
            }
        }

        if (trueCount == 0) {
            throw new BusinessException("至少要包含一个正确项！");
        }


        //单选题
        if (qu.getQuType().equals(QuType.RADIO) && trueCount > 1) {
            throw new BusinessException("单选题不能包含多个正确项！");
        }

    }

    /**
     * 试题-查
     * @param req201009
     * @return
     */
    public Object getQuById(Req201009 req201009) {
        //查询题目信息
        ElQu elqu = getById(req201009.getId());

        //查询题目的答案
        LambdaQueryWrapper<ElQuAnswer> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ElQuAnswer::getQuId,req201009.getId());
        List<ElQuAnswer> list1 = elQuAnswerService.list(qw1);

        //查询题目所属的题库
        LambdaQueryWrapper<ElQuRepo> qw2 = new LambdaQueryWrapper<>();
        qw2.eq(ElQuRepo::getQuId,req201009.getId());
        List<ElQuRepo> list2 = elQuRepoService.list(qw2);
        List<String> list3 = new ArrayList<>();
        list2.forEach(x->{
            list3.add(x.getRepoId());
        });

        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(elqu));

        map.put("answerList",list1);
        map.put("repoIds",list3);

        return map;
    }

    public Object delQuByIds(Req201010 req201010) {
        //删试题表
        this.removeByIds(req201010.getIds());

        //删答案表
        LambdaQueryWrapper<ElQuAnswer> qw1 = new LambdaQueryWrapper<>();
        qw1.in(ElQuAnswer::getQuId,req201010.getIds());
        elQuAnswerService.remove(qw1);

        //删 试题-题库 关系表
        LambdaQueryWrapper<ElQuRepo> qw2 = new LambdaQueryWrapper<>();
        qw2.in(ElQuRepo::getQuId,req201010.getIds());
        elQuRepoService.remove(qw2);

        return "Success";
    }

    /**
     * 试题-批量增加/移出题库
     * @param req201011
     * @return
     */
    public Object batchOperation(Req201011 req201011) {
        // 移除的
        if(req201011.isRemove()){
            QueryWrapper<ElQuRepo> wrapper = new QueryWrapper<>();
            wrapper.lambda()
                    .in(ElQuRepo::getRepoId, req201011.getRepoIds())
                    .in(ElQuRepo::getQuId, req201011.getQuIds());
            elQuRepoService.remove(wrapper);
        }else{
            // 新增的
            for(String quId : req201011.getQuIds()){
                ElQu q = this.getById(quId);
                elQuRepoService.saveAll(quId, q.getQuType(), req201011.getRepoIds());
            }
        }

        for(String id: req201011.getRepoIds()){
            elQuRepoService.sortRepo(id);
        }
        return "Success";
    }

    public List<ElQu> listByRandom(String repoId, Integer quType, Integer level, List<String> excludes, Integer size) {
        return baseMapper.listByRandom(repoId, quType, level, excludes, size);
    }
}
